//
//  MotionData.h
//
//  Created by Michael Bethany on 5/13/10.
//  Copyright 2010 __PicklePumpers__. All rights reserved.
//
//	Handles retrieving Sudden Motion Sensor data and storing it.
//	Mostly it just adds an event to the way data retrieval works. 
//	It still has to poll but hides that from you.
//

#import "MotionData.h"
#import "unimotion.h"

NSString * const PPIMotionNotification = @"PPIMotion";

@implementation MotionData

-(id)initWithEnabled:(BOOL)enabledValue timerFrequency:(float)frequency
{
	[super init];
	enabled = enabledValue;
	[self setTimerFrequency:frequency];
	return self;
}

-(id)initWithEnabled:(BOOL)enabledValue
{
	return [self initWithEnabled:enabledValue timerFrequency:1.0];
}

-(id)init
{
	return [self initWithEnabled:NO];
}

// If the timer is enabled
-(BOOL)enabled
{
	return enabled;
}

// If the data is valid
-(BOOL)valid
{
	return valid;
}

// enabled property accessor
-(void)setEnabled:(BOOL)enabledValue
{
	smsType = detect_sms();
	
	// Don't allow timer to be enabled if there's no sudden motion sensor
	if (!smsType)
	{ enabledValue = NO; }
	
	enabled = enabledValue;
	
	// Reset XYZ - Can't be 512 so that should be a clue to anything using the data
	X = 512;
	Y = 512;
	Z = 512;
	valid = NO;
	
	// Turn off the timer if it exists, we always do this
	if (readTimer != nil)
	{
		[readTimer invalidate];
		[readTimer release];
		readTimer = nil;
	}
	
	// Turn on the timer if enabled
	if (enabled)
	{
		readTimer = [NSTimer scheduledTimerWithTimeInterval:timerFrequency target:self selector:@selector(readData) userInfo:nil repeats:YES];
	}
	
}

// Reads data from the sms sensor
-(void)readData
{
	int newX, newY, newZ;
	read_sms_scaled(smsType, &newX, &newY, &newZ);

	// Ignore tiny changes due to inaccuracy of the SMS device
	BOOL bigChange = (abs(X-newX) > 10 || abs(Y-newY) > 10 || abs(Z-newZ) > 10);
	X = newX;
	Y = newY;
	Z = newZ;
	if (bigChange)
	{
		// Post notifiction if data changed significantly
		NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
		[nc postNotificationName:PPIMotionNotification object:nil];
	}
}

// X axis
-(int)X
{
	return X;
}

// Y axis
-(int)Y
{
	return Y;
}

// Z axis
-(int)Z
{
	return Z;
}

// Read the current timer frequency
-(float)timerFrequency
{
	return timerFrequency;
}

// Reset the timer frequency
-(void)setTimerFrequency:(float)frequency
{
	// Reset the timer if the frequecy is different
	if (frequency != timerFrequency)
	{
		timerFrequency = frequency;
		[self setEnabled:enabled];
	}
}

@end
